package com.zql.config;

import com.zql.Configuration;
import com.zql.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private final Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException,
            ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> elementList = rootElement.selectNodes("select");
        elementList.addAll(rootElement.selectNodes("insert"));
        elementList.addAll(rootElement.selectNodes("update"));
        elementList.addAll(rootElement.selectNodes("delete"));
        for (Element element : elementList) {
            //id的值
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");

            //封装mappedStatement
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setSqlCommandType(element.getQName().getName());
            if (paramterType != null) {
                //输入参数class
                Class<?> paramterTypeClass = getClassType(paramterType);
                mappedStatement.setParamterType(paramterTypeClass);
            }

            if (resultType != null) {
                //返回结果class
                Class<?> resultTypeClass = getClassType(resultType);
                mappedStatement.setResultType(resultTypeClass);
            }
            //sql语句
            String sqlTextTrim = element.getTextTrim();
            mappedStatement.setSql(sqlTextTrim);
            //statement.Id
            String key = namespace + "." + id;
            //填充configuration
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        Class<?> aClass = Class.forName(paramterType);
        return aClass;
    }
}
